{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "view-in-github",
    "colab_type": "text"
   },
   "source": [
    "<a href=\"https://colab.research.google.com/github/alexfazio/crewAI-quickstart/blob/main/crewai_example_collaboration_financial_analysis_quickstart.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "65GBAFDXpte9"
   },
   "source": "# Multi-agent Collaboration for Financial Analysis"
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "KyFD2Twopte-"
   },
   "source": [
    "If you're running this notebook on your own machine, you can install the following:\n",
    "```Python\n",
    "!pip install crewai==0.28.8 crewai_tools==0.1.6 langchain_community==0.0.29 --quiet\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 64,
    "id": "KBtSUwo7pte-"
   },
   "outputs": [],
   "source": [
    "# Warning control\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "_DtetBg4pte-"
   },
   "source": [
    "- Import libraries, APIs and LLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 30,
    "id": "R1bQgOSopte_"
   },
   "outputs": [],
   "source": [
    "from crewai import Agent, Task, Crew"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rLsDKyuZpte_"
   },
   "source": [
    "**Note**:\n",
    "- The video uses `gpt-4o`, but due to certain constraints, and in order to offer this course for free to everyone, the code you'll run here will use `gpt-3.5-turbo`.\n",
    "- You can use `gpt-4o` when you run the notebook _locally_ (using `gpt-4o` will not work on the platform)\n",
    "- Thank you for your understanding!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 115,
    "id": "wEGgKxVPpte_"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "from utils import get_openai_api_key, get_serper_api_key\n",
    "\n",
    "openai_api_key = get_openai_api_key()\n",
    "os.environ[\"OPENAI_MODEL_NAME\"] = 'gpt-3.5-turbo'\n",
    "os.environ[\"SERPER_API_KEY\"] = get_serper_api_key()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "oZIcaQj3pte_"
   },
   "source": [
    "## crewAI Tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 81,
    "id": "RDsThA14pte_"
   },
   "outputs": [],
   "source": [
    "from crewai_tools import ScrapeWebsiteTool, SerperDevTool\n",
    "\n",
    "search_tool = SerperDevTool()\n",
    "scrape_tool = ScrapeWebsiteTool()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "OpWxj4iXpte_"
   },
   "source": [
    "## Creating Agents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 234,
    "id": "Au0wKrgApte_"
   },
   "outputs": [],
   "source": [
    "data_analyst_agent = Agent(\n",
    "    role=\"Data Analyst\",\n",
    "    goal=\"Monitor and analyze market data in real-time \"\n",
    "         \"to identify trends and predict market movements.\",\n",
    "    backstory=\"Specializing in financial markets, this agent \"\n",
    "              \"uses statistical modeling and machine learning \"\n",
    "              \"to provide crucial insights. With a knack for data, \"\n",
    "              \"the Data Analyst Agent is the cornerstone for \"\n",
    "              \"informing trading decisions.\",\n",
    "    verbose=True,\n",
    "    allow_delegation=True,\n",
    "    tools = [scrape_tool, search_tool]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 234,
    "id": "Gya_cvO1pte_"
   },
   "outputs": [],
   "source": [
    "trading_strategy_agent = Agent(\n",
    "    role=\"Trading Strategy Developer\",\n",
    "    goal=\"Develop and test various trading strategies based \"\n",
    "         \"on insights from the Data Analyst Agent.\",\n",
    "    backstory=\"Equipped with a deep understanding of financial \"\n",
    "              \"markets and quantitative analysis, this agent \"\n",
    "              \"devises and refines trading strategies. It evaluates \"\n",
    "              \"the performance of different approaches to determine \"\n",
    "              \"the most profitable and risk-averse options.\",\n",
    "    verbose=True,\n",
    "    allow_delegation=True,\n",
    "    tools = [scrape_tool, search_tool]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 234,
    "id": "f-J7TIc9pte_"
   },
   "outputs": [],
   "source": [
    "execution_agent = Agent(\n",
    "    role=\"Trade Advisor\",\n",
    "    goal=\"Suggest optimal trade execution strategies \"\n",
    "         \"based on approved trading strategies.\",\n",
    "    backstory=\"This agent specializes in analyzing the timing, price, \"\n",
    "              \"and logistical details of potential trades. By evaluating \"\n",
    "              \"these factors, it provides well-founded suggestions for \"\n",
    "              \"when and how trades should be executed to maximize \"\n",
    "              \"efficiency and adherence to strategy.\",\n",
    "    verbose=True,\n",
    "    allow_delegation=True,\n",
    "    tools = [scrape_tool, search_tool]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 234,
    "id": "QAz-khxkpte_"
   },
   "outputs": [],
   "source": [
    "risk_management_agent = Agent(\n",
    "    role=\"Risk Advisor\",\n",
    "    goal=\"Evaluate and provide insights on the risks \"\n",
    "         \"associated with potential trading activities.\",\n",
    "    backstory=\"Armed with a deep understanding of risk assessment models \"\n",
    "              \"and market dynamics, this agent scrutinizes the potential \"\n",
    "              \"risks of proposed trades. It offers a detailed analysis of \"\n",
    "              \"risk exposure and suggests safeguards to ensure that \"\n",
    "              \"trading activities align with the firm’s risk tolerance.\",\n",
    "    verbose=True,\n",
    "    allow_delegation=True,\n",
    "    tools = [scrape_tool, search_tool]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "tWcxt1vfpte_"
   },
   "source": [
    "## Creating Tasks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 251,
    "id": "OSVfRdEepte_"
   },
   "outputs": [],
   "source": [
    "# Task for Data Analyst Agent: Analyze Market Data\n",
    "data_analysis_task = Task(\n",
    "    description=(\n",
    "        \"Continuously monitor and analyze market data for \"\n",
    "        \"the selected stock ({stock_selection}). \"\n",
    "        \"Use statistical modeling and machine learning to \"\n",
    "        \"identify trends and predict market movements.\"\n",
    "    ),\n",
    "    expected_output=(\n",
    "        \"Insights and alerts about significant market \"\n",
    "        \"opportunities or threats for {stock_selection}.\"\n",
    "    ),\n",
    "    agent=data_analyst_agent,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 268,
    "id": "KAbnRbRJpte_"
   },
   "outputs": [],
   "source": [
    "# Task for Trading Strategy Agent: Develop Trading Strategies\n",
    "strategy_development_task = Task(\n",
    "    description=(\n",
    "        \"Develop and refine trading strategies based on \"\n",
    "        \"the insights from the Data Analyst and \"\n",
    "        \"user-defined risk tolerance ({risk_tolerance}). \"\n",
    "        \"Consider trading preferences ({trading_strategy_preference}).\"\n",
    "    ),\n",
    "    expected_output=(\n",
    "        \"A set of potential trading strategies for {stock_selection} \"\n",
    "        \"that align with the user's risk tolerance.\"\n",
    "    ),\n",
    "    agent=trading_strategy_agent,\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 251,
    "id": "Y370kpDtpte_"
   },
   "outputs": [],
   "source": [
    "# Task for Trade Advisor Agent: Plan Trade Execution\n",
    "execution_planning_task = Task(\n",
    "    description=(\n",
    "        \"Analyze approved trading strategies to determine the \"\n",
    "        \"best execution methods for {stock_selection}, \"\n",
    "        \"considering current market conditions and optimal pricing.\"\n",
    "    ),\n",
    "    expected_output=(\n",
    "        \"Detailed execution plans suggesting how and when to \"\n",
    "        \"execute trades for {stock_selection}.\"\n",
    "    ),\n",
    "    agent=execution_agent,\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 251,
    "id": "4cFzLUW4pte_"
   },
   "outputs": [],
   "source": [
    "# Task for Risk Advisor Agent: Assess Trading Risks\n",
    "risk_assessment_task = Task(\n",
    "    description=(\n",
    "        \"Evaluate the risks associated with the proposed trading \"\n",
    "        \"strategies and execution plans for {stock_selection}. \"\n",
    "        \"Provide a detailed analysis of potential risks \"\n",
    "        \"and suggest mitigation strategies.\"\n",
    "    ),\n",
    "    expected_output=(\n",
    "        \"A comprehensive risk analysis report detailing potential \"\n",
    "        \"risks and mitigation recommendations for {stock_selection}.\"\n",
    "    ),\n",
    "    agent=risk_management_agent,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "sg91wwKNptfA"
   },
   "source": [
    "## Creating the Crew\n",
    "- The `Process` class helps to delegate the workflow to the Agents (kind of like a Manager at work)\n",
    "- In the example below, it will run this hierarchically.\n",
    "- `manager_llm` lets you choose the \"manager\" LLM you want to use."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 353,
    "id": "HTfi3mP4ptfA"
   },
   "outputs": [],
   "source": [
    "from crewai import Crew, Process\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# Define the crew with agents and tasks\n",
    "financial_trading_crew = Crew(\n",
    "    agents=[data_analyst_agent,\n",
    "            trading_strategy_agent,\n",
    "            execution_agent,\n",
    "            risk_management_agent],\n",
    "\n",
    "    tasks=[data_analysis_task,\n",
    "           strategy_development_task,\n",
    "           execution_planning_task,\n",
    "           risk_assessment_task],\n",
    "\n",
    "    manager_llm=ChatOpenAI(model=\"gpt-3.5-turbo\",\n",
    "                           temperature=0.7),\n",
    "    process=Process.hierarchical,\n",
    "    verbose=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "SoeN-QB7ptfA"
   },
   "source": [
    "## Running the Crew\n",
    "\n",
    "- Set the inputs for the execution of the crew."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 149,
    "id": "-qoJrZ13ptfA"
   },
   "outputs": [],
   "source": [
    "# Example data for kicking off the process\n",
    "financial_trading_inputs = {\n",
    "    'stock_selection': 'AAPL',\n",
    "    'initial_capital': '100000',\n",
    "    'risk_tolerance': 'Medium',\n",
    "    'trading_strategy_preference': 'Day Trading',\n",
    "    'news_impact_consideration': True\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bcUVMiLkptfA"
   },
   "source": [
    "**Note**: LLMs can provide different outputs for they same input, so what you get might be different than what you see in the video."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 47,
    "id": "PMQ3Ji5CptfA"
   },
   "outputs": [],
   "source": [
    "### this execution will take some time to run\n",
    "result = financial_trading_crew.kickoff(inputs=financial_trading_inputs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bo5RwgpxptfA"
   },
   "source": [
    "- Display the final result as Markdown."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "height": 47,
    "id": "L0TX5zusptfA"
   },
   "outputs": [],
   "source": [
    "# @title 🖥️ Display the results of your crew as markdown\n",
    "from IPython.display import display, Markdown\n",
    "\n",
    "markdown_text = result.raw  # Adjust this based on the actual attribute\n",
    "\n",
    "# Display the markdown content\n",
    "display(Markdown(markdown_text))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  },
  "colab": {
   "provenance": [],
   "include_colab_link": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
